import { X_TOKEN, OK, TOKEN_INVALID } from "./constant";
import { BASE_URL } from "./env";
import { Response, LoginSchema } from "./schema";

export const login = () : Promise<boolean> => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			scopes: 'auth_base',
			onlyAuthorize: true,
			success: async loginRes => {
				const response : Response<LoginSchema> = await post<LoginSchema>("/login", { code: loginRes.code })
				if (response.code === OK) {
					uni.setStorageSync(X_TOKEN, response.data.token)
					resolve(true)
				} else {
					uni.showModal({
						title: response.message
					})
					reject(response)
				}
			}
		})
	})
}

export const post = <T>(path : string, body : any) => {
	return new Promise<Response<T>>((resolve) => {
		uni.request({
			url: BASE_URL + path,
			method: 'POST',
			data: body,
			header: {
				'content-type': 'application/json',
				'x-token': uni.getStorageSync(X_TOKEN)
			},
			success: async res => {
				const data : Response<T> = (res.data as Response<T>)
				if (data.code === TOKEN_INVALID) {
					await login()
					resolve(post(path, body))
					return
				}
				resolve(data)
			}
		})
	})
}

export const get = <T>(path : string, body : any = null) => {
	return new Promise<Response<T>>((resolve) => {
		uni.request({
			url: BASE_URL + path,
			method: 'GET',
			data: body,
			header: {
				'x-token': uni.getStorageSync(X_TOKEN)
			},
			success: async res => {
				const data : Response<T> = (res.data as Response<T>)
				if (data.code === TOKEN_INVALID) {
					await login()
					resolve(get(path, body))
					return
				}
				resolve(data)
			}
		})
	})
}

export const uploadFile = <T>(filePath : string) => {
	return new Promise<Response<T>>((resolve) => {
		uni.uploadFile({
			url: BASE_URL + "/file/upload",
			filePath: filePath,
			name: 'file',
			header: {
				'x-token': uni.getStorageSync(X_TOKEN)
			},
			success: async (uploadFileRes) => {
				const data = JSON.parse(uploadFileRes.data) as Response<T>
				if (data.code === TOKEN_INVALID) {
					await login()
					resolve(upload(filePath))
					return
				}
				resolve(data)
			}
		})
	})
}